package com.yonyou.brigade.util.mail;

import com.yonyou.ybzboot.starter.mail.model.Email;
import com.yonyou.ybzboot.starter.mail.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 邮件发送工具类
 *
 * @author admin
 * @since 2019-04-04
 */
@Slf4j
@Component
public class MailSenderUtil {

    @Autowired
    private IMailService mailService;

    public static MailSenderUtil mailSenderUtil;

    @PostConstruct
    public void init() {
        mailSenderUtil = this;
    }


    public static void testSendEmail() throws Exception {
        Email email = new Email();
        email.setEmail(new String[]{"xuexmf@yonyou.com"});
        email.setSubject("测试邮件");
        email.setContent("邮件发送测试");

        mailSenderUtil.mailService.send(email);
    }

    public static void sendExceptionMail(String[] to, Throwable e) {
        Email email = new Email(to, "Exception Warning", e.getMessage(), null, null);
        log.warn("异常提示邮件，异常内容：{}", e.getMessage());
        try {
            mailSenderUtil.mailService.send(email);
        } catch (Exception e1) {
            log.warn("邮件发送失败，接收人：{}，邮件主题：{}，邮件内容：{}", email.getEmail(), email.getSubject(), email.getContent());
        }
    }

    public static void sendCommonMail(List<String> to, String subject, String content) {
        Email email = new Email(to.toArray(new String[to.size()]), subject, content, null, null);
        log.info("普通邮件发送，接收人：{}，邮件主题：{}，邮件内容：{}", email.getEmail(), email.getSubject(), email.getContent());
        try {
            mailSenderUtil.mailService.send(email);
        } catch (Exception e) {
            log.warn("邮件发送失败，接收人：{}，邮件主题：{}，邮件内容：{}", email.getEmail(), email.getSubject(), email.getContent());
        }
    }
}
